package cn.iocoder.yudao.module.wine.controller.app.businessuser;

import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.ip.core.Area;
import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.framework.ip.core.utils.InfoAreaUtils;
import cn.iocoder.yudao.module.system.controller.admin.ip.vo.AreaNodeRespVO;
import cn.iocoder.yudao.module.wine.controller.admin.businessuser.vo.BusinessUserRespVO;
import cn.iocoder.yudao.module.wine.controller.app.businessuser.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.businesscredit.BusinessCreditDO;
import cn.iocoder.yudao.module.wine.dal.dataobject.config.WineConfigDO;
import cn.iocoder.yudao.module.wine.service.businesscredit.BusinessCreditService;
import cn.iocoder.yudao.module.wine.service.businessuser.BusinessUserService;
import cn.iocoder.yudao.module.wine.service.config.WineConfigService;
import cn.iocoder.yudao.module.wine.service.userfans.UserFansService;
import cn.iocoder.yudao.module.wine.service.uservisitor.UserVisitorService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;

import java.time.LocalDateTime;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * @author zyc
 * @createDate 2024/4/23 10:48
 */
@Tag(name = "用户 APP - 商家模块")
@RestController
@RequestMapping("/wine/business-user")
@Validated
public class AppBusinessUserController {

    @Resource
    private BusinessUserService businessUserService;

    @Resource
    private UserVisitorService userVisitorService;

    @Resource
    private UserFansService userFansService;

    @Resource
    private BusinessCreditService businessCreditService;

    @Resource
    private WineConfigService configService;

    /**
     * 商家入驻
     * @param createReqVO
     * @return
     */
    @PostMapping("/create")
    @PermitAll
    @Operation(summary = "商家入驻")
    public CommonResult<Integer> createBusinessUser(@Valid @RequestBody AppBusinessUserSaveReqVO createReqVO) {
        return success(businessUserService.appCreateBusinessUser(createReqVO));
    }

    /**
     * 商家修改
     * @param createReqVO
     * @return
     */
    @PostMapping("/update")
    @Operation(summary = "商家修改")
    public CommonResult<Integer> update(@Valid @RequestBody AppBusinessUserUpdateReqVO createReqVO) {
        return success(businessUserService.appUpdateBusinessUser(createReqVO));
    }

    /**
     * 个人申请团长入驻
     * @param createReqVO
     * @return
     */
    @PostMapping("/create-team")
    @PermitAll
    @Operation(summary = "团长申请")
    public CommonResult<Integer> createTeam(@Valid @RequestBody AppBusinessUserSaveReqVO createReqVO) {
        return success(businessUserService.appCreateBusinessUserTeam(createReqVO));
    }

    /**
     * 商家认证后申请成为商家团长
     * @param createReqVO
     * @return
     */
    @PostMapping("/create-team-simple")
    @Operation(summary = "团长申请")
    public CommonResult<Integer> createTeamSimple(@Valid @RequestBody AppBusinessUserSaveReqVO createReqVO) {
        return success(businessUserService.appCreateBusinessUserTeamSimple(createReqVO));
    }

    /**
     * 发送手机验证码
     * @param reqVO
     * @return
     */
    @PostMapping("/send-sms-code")
    @PermitAll
    @Operation(summary = "发送手机验证码")
    public CommonResult<Boolean> sendSmsCode(@RequestBody @Valid RegisterSmsSendReqVO reqVO) {
        businessUserService.sendSmsCode(reqVO);
        return success(true);
    }

    /**
     * 校验手机验证码
     * @param reqVO
     * @return
     */
    @PostMapping("/validate-sms-code")
    @PermitAll
    @Operation(summary = "校验手机验证码")
    public CommonResult<Boolean> validateSmsCode(@RequestBody @Valid RegisterSmsSendReqVO reqVO) {
        businessUserService.validateSmsCode(getLoginUserId(), reqVO);
        return success(true);
    }

    /**
     * 获得地区树
     * @return
     */
    @GetMapping("/tree")
    @Operation(summary = "获得地区树")
    public CommonResult<List<AreaNodeRespVO>> getAreaTree() {
        Area area = InfoAreaUtils.getArea(Area.ID_CHINA);
        Assert.notNull(area, "获取不到中国");
        return success(BeanUtils.toBean(area.getChildren(), AreaNodeRespVO.class));
    }

    /**
     * 获得所有地区树
     * @return
     */
    @GetMapping("/all-tree")
    @Operation(summary = "获得所有地区树")
    public CommonResult<List<AreaNodeRespVO>> getAllAreaTree() {
        Area area = AreaUtils.getArea(Area.ID_CHINA);
        Assert.notNull(area, "获取不到中国");
        return success(BeanUtils.toBean(area.getChildren(), AreaNodeRespVO.class));
    }

    /**
     * 查看用户信息
     * @param id
     * @return
     */
    @GetMapping("/info")
    @Operation(summary = "查看用户信息")
    @PermitAll
    public CommonResult<BusinessUserRespVO> getBusinessUserInfo(@RequestParam("id") Long id) {
        BusinessUserRespVO businessUser = businessUserService.appGetBusinessUser(id);
        //访客数量
        Long visitorNum = userVisitorService.getVisitorNum(id);
        Long fansNum = userFansService.getFansNum(id);
        Long subscribeNum = userFansService.getSubscribeNum(id);
        //新增权限控制数据字段
        Integer creditId = businessUser.getCreditId();
        if (creditId == 0) {
            creditId = 1;
        }
        //权限降级处理
        LocalDateTime nowTime = LocalDateTime.now();
        if(creditId==3) {
            //商家团长:判断团长过期时间,过期后先降至VIP商家权限，如果VIP商家还过期了则降至入驻商家权限
            LocalDateTime teamOverTime = businessUser.getTeamOverTime();
            if (teamOverTime!=null) {
                if (teamOverTime.isBefore(nowTime)) {
                    //过期,降至VIP商家权限
                    creditId = 2;
                }
            }
            else {
                creditId = 2;//已审核，没有交团费
            }
        }
        // 如果团长没过期，VIP商家过期了，也降至入驻商家权限
        if(creditId==2 || creditId==3) {
            //VIP商家:判断商家过期时间
            LocalDateTime busiOverTime = businessUser.getOverTime();
            if (busiOverTime!=null && busiOverTime.isBefore(nowTime)) {
                //过期,降至入驻商家权限
                creditId = 1;
            }
        }
        businessUser.setCreditTrueId(creditId);
        //账户模块权限
        BusinessCreditDO businessCreditDO = businessCreditService.getBusinessCreditByLevel(creditId);
        if (businessCreditDO != null) {
            businessUser.setModular(businessCreditDO.getModular().toString());
        }

        //模块权限
        WineConfigDO wineConfigDO = configService.getOne();
        if (wineConfigDO != null) {
            businessUser.setIsOpenUse(wineConfigDO.getIsOpenUse());
            businessUser.setCloseTime(wineConfigDO.getCloseTime());
            businessUser.setFreeMonth(wineConfigDO.getFreeMonth());
            businessUser.setIsOpenMonth(wineConfigDO.getIsOpenMonth());
        }

        businessUser.setFansNum(fansNum);
        businessUser.setSubscribeNum(subscribeNum);
        businessUser.setVisitorNum(visitorNum);
        String format = AreaUtils.format(businessUser.getAreaId(), " ");
        businessUser.setAreaName(format);
        return success(businessUser);
    }

    /**
     * 通过手机号查看用户信息
     * @param mobile
     * @return
     */
    @GetMapping("/info-mobile")
    @Operation(summary = "通过手机号查看用户信息")
    @PermitAll
    public CommonResult<AppUserAddressRespVO> getBusinessUserInfo(@RequestParam("mobile") String mobile) {
        AppUserAddressRespVO businessUser = businessUserService.appGetBusinessUserByMobile(mobile);
        if(businessUser!=null) {

            //新增权限控制数据字段
            Integer creditId = businessUser.getCreditId();
            if (creditId == 0) {
                creditId = 1;
            }
            //权限降级处理
            LocalDateTime nowTime = LocalDateTime.now();
            if(creditId==3) {
                //商家团长:判断团长过期时间,过期后先降至VIP商家权限，如果VIP商家还过期了则降至入驻商家权限
                LocalDateTime teamOverTime = businessUser.getTeamOverTime();
                if (teamOverTime!=null) {
                    if (teamOverTime.isBefore(nowTime)) {
                        //过期,降至VIP商家权限
                        creditId = 2;
                    }
                }
                else {
                    creditId = 2;//已审核，没有交团费
                }
            }
            // 如果团长没过期，VIP商家过期了，也降至入驻商家权限
            if(creditId==2 || creditId==3) {
                //VIP商家:判断商家过期时间
                LocalDateTime busiOverTime = businessUser.getOverTime();
                if (busiOverTime!=null && busiOverTime.isBefore(nowTime)) {
                    //过期,降至入驻商家权限
                    creditId = 1;
                }
            }
            businessUser.setCreditTrueId(creditId);
            //账户模块权限
            BusinessCreditDO businessCreditDO = businessCreditService.getBusinessCreditByLevel(creditId);
            if (businessCreditDO != null) {
                businessUser.setModular(businessCreditDO.getModular().toString());
              }

            //模块权限
            WineConfigDO wineConfigDO = configService.getOne();
            if (wineConfigDO != null) {
                businessUser.setIsOpenUse(wineConfigDO.getIsOpenUse());
                businessUser.setCloseTime(wineConfigDO.getCloseTime());
                businessUser.setFreeMonth(wineConfigDO.getFreeMonth());
                businessUser.setIsOpenMonth(wineConfigDO.getIsOpenMonth());
            }
        }

        return success(businessUser);
    }

    /**
     * 查询团长下面的商家（列表）
     * @param type
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "查询团长下面的商家（列表）")
    public CommonResult<List<AppBusinessUserRespVO>> getBusinessUserList(@RequestParam("type") Integer type) {
        List<AppBusinessUserRespVO> list = businessUserService.appGetBusinessUserList(type);
        return success(list);
    }

    /**
     * 查询团长下面的商家收益信息
     * @param settlement
     * @return
     */
    @GetMapping("/earnings-list")
    @Operation(summary = "查询团长下面的商家收益信息")
    @Parameter(name = "settlement", description = "是否结算", required = true, example = "1 已结算 2未结算")
    public CommonResult<List<AppBusinessUserRespVO>> getBusinessUserEarningsList(@RequestParam("settlement") Integer settlement) {
        List<AppBusinessUserRespVO> list = businessUserService.appGetBusinessUserEarningsList(settlement);
        return success(list);
    }

    /**
     * 用户修改密码
     * @param passwordVO
     * @return
     */
    @PostMapping("/update-password")
    @Operation(summary = "用户修改密码")
    public CommonResult<Integer> updatePassword(@RequestBody @Valid AppUserUpdatePasswordVO passwordVO) {
        return success(businessUserService.updatePassword(passwordVO));
    }
}
